package com.example.plus.file.copyCharset.action;

import com.example.plus.file.comm.util.IoUtil;

import java.io.*;

/**
 * @author zhouxl
 * @DATE 2020/12/10
 * @descriptoin
 */
public class FileCharsetCopyAction {


    /**
     * 复制文件
     *
     * @param inPath        源文件的地址信息
     * @param outPath       输出的文件地址信息
     * @param sourceCharset 源文件的编码
     * @param targetCharset 复制的目标的文件编码
     */
    public void copyFile(String inPath,
                         String sourceCharset,
                         String outPath,
                         String targetCharset) throws Exception {
        File file = new File(inPath);
        BufferedReader reader = null;
        BufferedWriter writer = null;
        if (file.isFile()) {
            outPath = outPath + File.separator + file.getName();
            File temp = new File(outPath);
            if (!temp.exists()) {
                temp.createNewFile();
            }
            reader = IoUtil.bufferedReader(new InputStreamReader(new FileInputStream(file.getAbsoluteFile()), sourceCharset));
            writer = IoUtil.bufferedWriter(new OutputStreamWriter(new FileOutputStream(outPath), targetCharset));
            String line = null;
            while ((line = reader.readLine()) != null) {
                writer.write(line);
                writer.newLine();
            }
            writer.flush();
            // 关闭流信息
            IoUtil.closeable(reader, writer);
        } else {
            File temp = new File(outPath + File.separator + file.getName());
            if (!temp.exists()) {
                temp.mkdirs();
            }
            File[] files = file.listFiles();
            for (File f : files) {
                copyFile(f.getAbsolutePath(), sourceCharset, outPath + File.separator + file.getName(), targetCharset);
            }
        }
    }

}
